import time
import os
import csv

print("欢迎使用BMR计算器！")
def calculate_BMR(gender, height, age, weight):
    if gender == '男':
        BMR = 88.362 + (13.397 * weight) + (4.799 * height) - (5.677 * age)
    elif gender == '女':
        BMR = 447.593 + (9.247 * weight) + (3.098 * height) - (4.330 * age)
    else:
        return None
    return BMR

def count():
    gender = input("请输入性别（男/女）：")
    if gender not in ['男','女']:
        print("性别输入有误，请重新输入！")
        return
    try:
        height = float(input("请输入身高（单位：cm）："))
        age = int(input("请输入年龄（岁）："))
        weight = float(input("请输入体重（单位：kg）："))
    except ValueError:
        print("输入有误，请重新输入！")
        return

    BMR = calculate_BMR(gender, height, age, weight)
    if BMR is None:
        print("性别输入有误，请重新输入！")
    else:
        print("您的BMR值为：{:.2f}".format(BMR))

        filename = 'BMR记录.csv'
        if not os.path.exists(filename):
            with open(filename, 'w', newline='') as f:
                writer = csv.writer(f)
                writer.writerow(['时间', '性别', '身高(cm)', '年龄(岁)', '体重(kg)', 'BMR值(千卡/天)'])
        with open(filename, 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([time.strftime('%Y-%m-%d %H:%M:%S'), gender, height, age, weight, BMR])

if __name__ == '__main__':
    while True:
        count()
        choice = input("已完成所有输入，是否退出：")
        if choice == '是':
            print("感谢使用BMR计算器！")
            break
        elif choice == '否':
            continue